﻿/*
 * @author: wizardc
 */

using Cysharp.Threading.Tasks;
using Dou.Utils;

namespace DouEditor.Resource
{
    /// <summary>
    /// AB 包打包工具类
    /// </summary>
    public static class AssetBundleBuildUtil
    {
        public const string SettingPath = "Assets/DouSettings/BuildSetting.asset";
        public const string RuleFileFolder = "Assets/DouSettings/BuildRule";

        /// <summary>
        /// 构建 AB 包
        /// </summary>
        public static async UniTask<bool> Build(PlatformType platform, BuildRule buildRule, bool isContrast)
        {
            var data = new BuildStepData
            {
                platform = platform,
                buildRule = buildRule,
                isContrast = isContrast,
            };
            
            var executor = new BuildStepExecutor();
            
            // 设定打包管线
            executor.AddStep(new BuildStep_Begin(true));
            executor.AddStep(new BuildStep_CreateAtlas());
            executor.AddStep(new BuildStep_ABBuild());
            executor.AddStep(new BuildStep_HotFixed());
            executor.AddStep(new BuildStep_End(true));

            if (!await executor.Execute(data))
            {
                Log.Error("打包失败：" + executor.error);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 构建安装包，这里不执行 AB 包生成的任何逻辑，单纯就是打安装包
        /// </summary>
        public static async UniTask<bool> BuildInstallationPackage(PlatformType platform, BuildRule buildRule)
        {
            var data = new BuildPackageStepData
            {
                platform = platform,
                buildRule = buildRule,
            };
            
            var executor = new BuildStepExecutor();
            
            // 设定打包管线
            executor.AddStep(new BuildStep_Begin(false));
            executor.AddStep(new BuildStep_LinkXml());
            executor.AddStep(new BuildStep_SetSceneParam());
            executor.AddStep(new BuildStep_BuildPackage());
            executor.AddStep(new BuildStep_End(false));
            
            if (!await executor.Execute(data))
            {
                Log.Error("打包失败：" + executor.error);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 一键构建 AB 包及安装包
        /// </summary>
        public static async UniTask<bool> OneKeyBuild(PlatformType platform, BuildRule buildRule)
        {
            if (await Build(platform, buildRule, false))
            {
                return await BuildInstallationPackage(platform, buildRule);
            }
            return false;
        }
    }
}
